package net.tycmc.cty.ctyms.timejob.iems.dao;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.configuration.ConfigurationException;

import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;
import com.tycmc.functions.util.DynamicReadConfig;

import net.tycmc.cty.ctyms.timejob.bean.LoadLine;
import net.tycmc.cty.ctyms.timejob.bean.LoadLines;
import net.tycmc.cty.ctyms.timejob.bean.LoadSubSectionUtil;
import net.tycmc.bulb.common.dao.IBaseDAO;
import net.tycmc.bulb.common.dao.ITransactionDAO;
import net.tycmc.bulb.common.util.DateUtil;
import net.tycmc.bulb.common.util.MapGetter;
import net.tycmc.bulb.common.util.StringUtil;
import net.tycmc.cty.ctyms.timejob.common.DateRegUtil;
import net.tycmc.cty.ctyms.timejob.common.EquipVersionCommon;
import net.tycmc.cty.ctyms.timejob.common.ListUtil;

/**
 * 载重统计DAO
 * @author chengshichao
 * 创建时间：2012-11-5
 */
public class LoadBurDAO {
	
	private IBaseDAO baseDAO;
	
	private ITransactionDAO tranDAO;
	/**
	 * @return the baseDAO
	 */
	public IBaseDAO getBaseDAO() {
		return baseDAO;
	}
	/**
	 * @param baseDAO the baseDAO to set
	 */
	public void setBaseDAO(IBaseDAO baseDAO) {
		this.baseDAO = baseDAO;
	}
	/**
	 * @return the tranDAO
	 */
	public ITransactionDAO getTranDAO() {
		return tranDAO;
	}
	/**
	 * @param tranDAO the tranDAO to set
	 */
	public void setTranDAO(ITransactionDAO tranDAO) {
		this.tranDAO = tranDAO;
	}
	
	/**
	 * 开始统计
	 * @param vclInfoList 有效设备
	 * 
	 * 更新历史 jiyongtian 20141208 不输出正常时的日志
	 */
	public void startStat(){
		List<Map<String,Object>> vclInfoList = this.getVclInfoList();
		//遍历List
		for(Map<String,Object> vclInfoMap:vclInfoList){
//			int iFlag = this.statLogic(vclInfoMap);
			int iFlag = this.startWork(vclInfoMap);
			switch (iFlag){
				case 0:
					System.out.println("["+DateUtil.toString(DateUtil.now(), "yyyy-MM-dd HH:mm:ss")+"-载重负荷统计]" +
							"---设备号："+MapGetter.getString(vclInfoMap, "VehicleNumber")+"昨日设备无定时信息！");
				break;
				case 1:
					/*System.out.println("["+DateUtil.toString(DateUtil.now(), "yyyy-MM-dd HH:mm:ss")+"-载重负荷统计]" +
							"---设备号："+MapGetter.getString(vclInfoMap, "VehicleNumber")+"统计成功！");*/
				break;
				case 2:
					System.out.println("["+DateUtil.toString(DateUtil.now(), "yyyy-MM-dd HH:mm:ss")+"-载重负荷统计]" +
							"---设备号："+MapGetter.getString(vclInfoMap, "VehicleNumber")+"统计异常_表Msg_LoadStat插入值异常！");
				break;
				case 3:
					System.out.println("["+DateUtil.toString(DateUtil.now(), "yyyy-MM-dd HH:mm:ss")+"-载重负荷统计]" +
							"---设备号："+MapGetter.getString(vclInfoMap, "VehicleNumber")+"无符合要求的统计数据或该设备未设置载重区间！");
				break;
				case 4:
					System.out.println("["+DateUtil.toString(DateUtil.now(), "yyyy-MM-dd HH:mm:ss")+"-载重负荷统计]" +
							"---设备号："+MapGetter.getString(vclInfoMap, "VehicleNumber")+"统计异常_表Msg_LoadStatLast插入值异常！");
				break;
			}
		}
	}
	/**载重统计采用最新的逻辑*/
	private int startWork(Map<String, Object> vclInfoMap) {
		int state = -1;
		Map<String,Object> loadSet = this.getAndDealLoadSetMap(MapGetter.getString(vclInfoMap, "VehicleID"));
		if(null==loadSet||loadSet.isEmpty()){
			state = 3;
		}else{
			//统计日期
			String statDate = DateUtil.addDay(-1);
			//查询上次统计
			Map<String,Object> preMap = this.getPreTime(MapGetter.getString(vclInfoMap, "VehicleID"));
			String preStatDate = null;
			if(null==preMap||preMap.isEmpty()){
				preStatDate = statDate;
			}else{
				preStatDate = MapGetter.getString(preMap, "MsgLSL_PreTime");;
				String defDays = "";
				try {
					defDays = DynamicReadConfig.getConfigProperty("config.properties", "loadCalDefDays");
				} catch (ConfigurationException e) {
				}
				if(!StringUtil.isValid(defDays)){//如果未定义delayDays 则默认为-90天
					defDays = "3";
				}
				//上次统计时间超过1天
				if(DateRegUtil.getDaysOfTimeDef(new String[]{preStatDate,DateUtil.addDay(-1)}) >= Integer.parseInt(defDays)){
					this.makePreTiming(vclInfoMap,preStatDate,preStatDate.substring(0, 10),loadSet);
					/*
					 * 缺少中间天数的处理：1、校验该设备中间天内是否有数据，2、如果有怎么处理  
					 */
					preStatDate = statDate;
				}
			}
			//获取上次统计至昨天24时的定时信息
			List<Map<String,Object>> timingSrc = this.getTimingMsgOfOneVcl(vclInfoMap,preStatDate,statDate+" 23:59:59");
			if(null==timingSrc||timingSrc.size()<=0){
				state = 0;
			}else{
				List<String> sqlList = new ArrayList<String>();//执行SQL集合
				List<Object[]> paramList = new ArrayList<Object[]>();//执行SQL参数集合
				/*载重业务分段*/
				List<Map<String,Object>> stopPstn = getPstnDataOfStopTiming(MapGetter.getString(vclInfoMap, "VehicleID"), preStatDate, statDate+" 23:59:59");
				List<Map<String,Object>> fenceList = getEnclosureByVclDBCodeAndAbove(vclInfoMap);
				LoadLines tLoadLines = null;
				tLoadLines = new LoadSubSectionUtil().adjustLoadThenSubSection(timingSrc, stopPstn, null, fenceList, loadSet, true);
				//LoadLines tLoadLines = LoadSubSectionUtil.loadSubSection(timingSrc,loadSet,null);
				List<LoadLine> tLL = tLoadLines.getLoadLines();
				//由于载重封装方法强制了最后一个分割点至最后一个源数据点为一段，因此tLL.size()>1时才处理，同时
				//在这里仅处理第一段至倒数第二段的数据
				if(tLL.size()>1){
					for(int i=0;i<(tLL.size()-1);i++){
						LoadLine oneLine = tLL.get(i);
						double runKm = oneLine.getValueByParamName("runKm");
						double MsgT_tRunKm = oneLine.getValueByParamName("MsgT_tRunKm");
						double MsgT_tRunKmExact = oneLine.getValueByParamName("MsgT_tRunKmExact");
						double MsgT_tRunKmECU = oneLine.getValueByParamName("MsgT_tRunKmECU");
						double MsgT_tRunKmExact_PGN = oneLine.getValueByParamName("MsgT_tRunKmExact_PGN");
						double VclP_Tmileag = oneLine.getValueByParamName("VclP_Tmileage");
						double runTime = oneLine.getValueByParamName("runTime");
						double oilCons = oneLine.getValueByParamName("oilCons");
						double avgLoad = oneLine.getValueByParamName("load");
						String[] timeDef = this.getTimeDefOfOneLoadLine(oneLine.getLoadSrcList());
						//执行SQL集合
						sqlList.add("insert into Msg_LoadStat (MsgLS_Vcl_ID,MsgLS_AvgLoad,MsgLS_SecKm,MsgLS_SecOilCon,MsgLS_SecTimeH," +
								"MsgLS_BgnTime,MsgLS_EndTime,MsgLS_StatTime,MsgLS_SecRunKmExact,MsgLS_SecRunKm,MsgLS_SecRunKmECU,MsgLS_SecMeterDistance,MsgLS_SecGPSDistance)values(?,?,?,?,?,?,?,?,?,?,?,?,?);");
						//执行SQL参数集合
						paramList.add(new Object[]{MapGetter.getString(vclInfoMap, "VehicleID"),avgLoad,runKm,oilCons,runTime,
								timeDef[0],timeDef[1],statDate,MsgT_tRunKmExact,MsgT_tRunKm,MsgT_tRunKmECU,MsgT_tRunKmExact_PGN,VclP_Tmileag});
					}//更新数据库，执行向Msg_LoadStat插入值的SQL
					boolean flag = tranDAO.batch(sqlList, paramList);
					String[] lastTimes = this.getTimeDefOfOneLoadLine(tLL.get(tLL.size()-2).getLoadSrcList());
					if(flag){
						//插入成功，则向Msg_LoadStatLast插入数据
						StringBuffer strBuff = new StringBuffer();
						int flagint = -1;
						if(null==preMap||preMap.isEmpty()){
							strBuff.append("insert into Msg_LoadStatLast(MsgLSL_Vcl_ID,MsgLSL_PreTime,MsgLSL_tLoad,MsgLSL_tLoadRunKmExact,MsgLSL_tLoadRunKm,MsgLSL_tLoadRunKmECU,MsgLSL_tLoadMeterDistance,MsgLSL_tLoadGPSDistance) ");
							strBuff.append("select ?,?,tLoad,tLoadRunKmExact,tLoadRunKm,tLoadRunKmECU,tLoadMeterDistance,tLoadGPSDistance from (select sum(MsgLS_AvgLoad*MsgLS_SecKm/1000) tLoad" +
									" ,sum(MsgLS_AvgLoad*MsgLS_SecRunKmExact/1000) tLoadRunKmExact,sum(MsgLS_AvgLoad*MsgLS_SecRunKm/1000) tLoadRunKm " +
									" ,sum(MsgLS_AvgLoad*MsgLS_SecRunKmECU/1000) tLoadRunKmECU,sum(MsgLS_AvgLoad*MsgLS_SecMeterDistance/1000) tLoadMeterDistance " +
									" ,sum(MsgLS_AvgLoad*MsgLS_SecGPSDistance/1000) tLoadGPSDistance from Msg_LoadStat ");
							strBuff.append("where MsgLS_Vcl_ID=? and MsgLS_StatTime=? ");
							strBuff.append("group by MsgLS_Vcl_ID) tmp");
							flagint = baseDAO.execInsert(strBuff.toString(), new Object[]{MapGetter.getString(vclInfoMap, "VehicleID"),lastTimes[1],MapGetter.getString(vclInfoMap, "VehicleID"),statDate});
						}else{
							String loadLastCheck = "select count(1) count from Msg_LoadStatLast where MsgLSL_Vcl_ID = ? ";
							Map<String,Object> chek = baseDAO.execQueryOne(loadLastCheck, new Object[]{MapGetter.getString(vclInfoMap, "VehicleID")});
							if(MapGetter.getString(chek, "count").equals("1")){
								strBuff.append("update Msg_LoadStatLast set MsgLSL_PreTime=?,");
								strBuff.append("MsgLSL_tLoad=( ");
								strBuff.append("select sum(MsgLS_AvgLoad*MsgLS_SecKm/1000) tLoad from Msg_LoadStat ");
								strBuff.append("where MsgLS_Vcl_ID=? and MsgLS_StatTime=? ");
								strBuff.append("group by MsgLS_Vcl_ID");
								strBuff.append(")+");
								strBuff.append("MsgLSL_tLoad, ");
								
								strBuff.append("MsgLSL_tLoadRunKmExact=( ");
								strBuff.append("select sum(MsgLS_AvgLoad*MsgLS_SecRunKmExact/1000) tLoad from Msg_LoadStat ");
								strBuff.append("where MsgLS_Vcl_ID=? and MsgLS_StatTime=? ");
								strBuff.append("group by MsgLS_Vcl_ID");
								strBuff.append(")+");
								strBuff.append("MsgLSL_tLoadRunKmExact, ");
								
								strBuff.append("MsgLSL_tLoadRunKm=( ");
								strBuff.append("select sum(MsgLS_AvgLoad*MsgLS_SecRunKm/1000) tLoad from Msg_LoadStat ");
								strBuff.append("where MsgLS_Vcl_ID=? and MsgLS_StatTime=? ");
								strBuff.append("group by MsgLS_Vcl_ID");
								strBuff.append(")+");
								strBuff.append("MsgLSL_tLoadRunKm, ");
								
								strBuff.append("MsgLSL_tLoadRunKmECU=( ");
								strBuff.append("select sum(MsgLS_AvgLoad*MsgLS_SecRunKmECU/1000) tLoad from Msg_LoadStat ");
								strBuff.append("where MsgLS_Vcl_ID=? and MsgLS_StatTime=? ");
								strBuff.append("group by MsgLS_Vcl_ID");
								strBuff.append(")+");
								strBuff.append("MsgLSL_tLoadRunKmECU,");
								
								strBuff.append("MsgLSL_tLoadMeterDistance=( ");
								strBuff.append("select sum(MsgLS_AvgLoad*MsgLS_SecMeterDistance/1000) tLoad from Msg_LoadStat ");
								strBuff.append("where MsgLS_Vcl_ID=? and MsgLS_StatTime=? ");
								strBuff.append("group by MsgLS_Vcl_ID");
								strBuff.append(")+");
								strBuff.append("MsgLSL_tLoadMeterDistance,");
								
								strBuff.append("MsgLSL_tLoadGPSDistance=( ");
								strBuff.append("select sum(MsgLS_AvgLoad*MsgLS_SecGPSDistance/1000) tLoad from Msg_LoadStat ");
								strBuff.append("where MsgLS_Vcl_ID=? and MsgLS_StatTime=? ");
								strBuff.append("group by MsgLS_Vcl_ID");
								strBuff.append(")+");
								strBuff.append("MsgLSL_tLoadGPSDistance ");
								
								strBuff.append("where MsgLSL_Vcl_ID=? ");
								flagint = baseDAO.execUpdate(strBuff.toString(), new Object[]{lastTimes[1],
									MapGetter.getString(vclInfoMap, "VehicleID"),statDate,
									MapGetter.getString(vclInfoMap, "VehicleID"),statDate,
									MapGetter.getString(vclInfoMap, "VehicleID"),statDate,
									MapGetter.getString(vclInfoMap, "VehicleID"),statDate,
									MapGetter.getString(vclInfoMap, "VehicleID"),statDate,
									MapGetter.getString(vclInfoMap, "VehicleID"),statDate,
									MapGetter.getString(vclInfoMap, "VehicleID")});
							}else{
								strBuff.append("insert into Msg_LoadStatLast(MsgLSL_Vcl_ID,MsgLSL_PreTime,MsgLSL_tLoad,MsgLSL_tLoadRunKmExact,MsgLSL_tLoadRunKm,MsgLSL_tLoadRunKmECU,MsgLSL_tLoadMeterDistance,MsgLSL_tLoadGPSDistance) ");						
								strBuff.append("select ?,?,* from (select sum(MsgLS_AvgLoad*MsgLS_SecKm/1000) tLoad ,sum(MsgLS_AvgLoad*MsgLS_SecRunKmExact/1000) tLoadRunKmExact,sum(MsgLS_AvgLoad*MsgLS_SecRunKm/1000) tLoadRunKm	");					
								strBuff.append(",sum(MsgLS_AvgLoad*MsgLS_SecRunKmECU/1000) tLoadRunKmECU,sum(MsgLS_AvgLoad*MsgLS_SecMeterDistance/1000) tLoadMeterDistance ,sum(MsgLS_AvgLoad*MsgLS_SecGPSDistance/1000) tLoadGPSDistance from Msg_LoadStat where MsgLS_Vcl_ID = ? and MsgLS_StatTime = ? )tmp ");
								flagint = baseDAO.execInsert(strBuff.toString(), new Object[]{
									MapGetter.getString(vclInfoMap, "VehicleID"),lastTimes[1],
									MapGetter.getString(vclInfoMap, "VehicleID"),statDate});
							}
						}
						if(flagint>0){
							state = 1;
						}else{
							state = 4;
						}
					}else{//向Msg_LoadStat插入值异常
						state = 2;
					}
				}else{//上一次查询时间至当天24时获取的定时信息，属于同一载重段，由于不确定这一段的结束位置，因此不想Msg_LoadStat表中插入数据
					state = 1;
				}
			}
		}
		return state;
	}
	/**
	 * 完成上次剩余的数据重新统计
	 * 如果上次统计完成到现在超过配置的天数时触发该方法，将上次未统计的数据进行统计
	 **/
	private void makePreTiming(Map<String, Object> vclInfoMap,String preStatDate, String statDate,Map<String,Object> loadSet) {
		List<Map<String,Object>> timingSrc = this.getTimingMsgOfOneVcl(vclInfoMap,preStatDate,statDate+" 23:59:59");
		if(null==timingSrc||timingSrc.size()<=0){
			
		}else{
			List<String> sqlList = new ArrayList<String>();//执行SQL集合
			List<Object[]> paramList = new ArrayList<Object[]>();//执行SQL参数集合
			/*载重业务分段*/
			List<Map<String,Object>> stopPstn = getPstnDataOfStopTiming(MapGetter.getString(vclInfoMap, "VehicleID"), preStatDate, statDate+" 23:59:59");
			List<Map<String,Object>> fenceList = getEnclosureByVclDBCodeAndAbove(vclInfoMap);
			LoadLines tLoadLines = null;
			tLoadLines = new LoadSubSectionUtil().adjustLoadThenSubSection(timingSrc, stopPstn, null, fenceList, loadSet, true);
			List<LoadLine> tLL = tLoadLines.getLoadLines();
			if(tLL.size()>0){
				for(int i=0;i<(tLL.size());i++){
					LoadLine oneLine = tLL.get(i);
					double runKm = oneLine.getValueByParamName("runKm");
					double MsgT_tRunKm = oneLine.getValueByParamName("MsgT_tRunKm");
					double MsgT_tRunKmExact = oneLine.getValueByParamName("MsgT_tRunKmExact");
					double MsgT_tRunKmECU = oneLine.getValueByParamName("MsgT_tRunKmECU");
					double MsgT_tRunKmExact_PGN = oneLine.getValueByParamName("MsgT_tRunKmExact_PGN");
					double VclP_Tmileag = oneLine.getValueByParamName("VclP_Tmileage");
					double runTime = oneLine.getValueByParamName("runTime");
					double oilCons = oneLine.getValueByParamName("oilCons");
					double avgLoad = oneLine.getValueByParamName("load");
					String[] timeDef = this.getTimeDefOfOneLoadLine(oneLine.getLoadSrcList());
					//执行SQL集合
					sqlList.add("insert into Msg_LoadStat (MsgLS_Vcl_ID,MsgLS_AvgLoad,MsgLS_SecKm,MsgLS_SecOilCon,MsgLS_SecTimeH," +
							"MsgLS_BgnTime,MsgLS_EndTime,MsgLS_StatTime,MsgLS_SecRunKmExact,MsgLS_SecRunKm,MsgLS_SecRunKmECU,MsgLS_SecMeterDistance,MsgLS_SecGPSDistance)values(?,?,?,?,?,?,?,?,?,?,?,?,?);");
					//执行SQL参数集合
					paramList.add(new Object[]{MapGetter.getString(vclInfoMap, "VehicleID"),avgLoad,runKm,oilCons,runTime,
							timeDef[0],timeDef[1],statDate,MsgT_tRunKmExact,MsgT_tRunKm,MsgT_tRunKmECU,MsgT_tRunKmExact_PGN,VclP_Tmileag});
				}//更新数据库，执行向Msg_LoadStat插入值的SQL
				boolean flag = tranDAO.batch(sqlList, paramList);
				String[] lastTimes = this.getTimeDefOfOneLoadLine(tLL.get(tLL.size()-1).getLoadSrcList());
				if(flag){
					String loadLastCheck = "select count(1) count from Msg_LoadStatLast where MsgLSL_Vcl_ID = ? ";
					Map<String,Object> chek = baseDAO.execQueryOne(loadLastCheck, new Object[]{MapGetter.getString(vclInfoMap, "VehicleID")});
					StringBuffer strBuff = new StringBuffer();
					if(MapGetter.getString(chek, "count").equals("1")){
						strBuff.append("update Msg_LoadStatLast set MsgLSL_PreTime=?,");
						strBuff.append("MsgLSL_tLoad=( ");
						strBuff.append("select sum(MsgLS_AvgLoad*MsgLS_SecKm/1000) tLoad from Msg_LoadStat ");
						strBuff.append("where MsgLS_Vcl_ID=? and MsgLS_StatTime=? ");
						strBuff.append("group by MsgLS_Vcl_ID");
						strBuff.append(")+");
						strBuff.append("MsgLSL_tLoad, ");
						
						strBuff.append("MsgLSL_tLoadRunKmExact=( ");
						strBuff.append("select sum(MsgLS_AvgLoad*MsgLS_SecRunKmExact/1000) tLoad from Msg_LoadStat ");
						strBuff.append("where MsgLS_Vcl_ID=? and MsgLS_StatTime=? ");
						strBuff.append("group by MsgLS_Vcl_ID");
						strBuff.append(")+");
						strBuff.append("MsgLSL_tLoadRunKmExact, ");
						
						strBuff.append("MsgLSL_tLoadRunKm=( ");
						strBuff.append("select sum(MsgLS_AvgLoad*MsgLS_SecRunKm/1000) tLoad from Msg_LoadStat ");
						strBuff.append("where MsgLS_Vcl_ID=? and MsgLS_StatTime=? ");
						strBuff.append("group by MsgLS_Vcl_ID");
						strBuff.append(")+");
						strBuff.append("MsgLSL_tLoadRunKm, ");
						
						strBuff.append("MsgLSL_tLoadRunKmECU=( ");
						strBuff.append("select sum(MsgLS_AvgLoad*MsgLS_SecRunKmECU/1000) tLoad from Msg_LoadStat ");
						strBuff.append("where MsgLS_Vcl_ID=? and MsgLS_StatTime=? ");
						strBuff.append("group by MsgLS_Vcl_ID");
						strBuff.append(")+");
						strBuff.append("MsgLSL_tLoadRunKmECU,");
						
						strBuff.append("MsgLSL_tLoadMeterDistance=( ");
						strBuff.append("select sum(MsgLS_AvgLoad*MsgLS_SecMeterDistance/1000) tLoad from Msg_LoadStat ");
						strBuff.append("where MsgLS_Vcl_ID=? and MsgLS_StatTime=? ");
						strBuff.append("group by MsgLS_Vcl_ID");
						strBuff.append(")+");
						strBuff.append("MsgLSL_tLoadMeterDistance,");
						
						strBuff.append("MsgLSL_tLoadGPSDistance=( ");
						strBuff.append("select sum(MsgLS_AvgLoad*MsgLS_SecGPSDistance/1000) tLoad from Msg_LoadStat ");
						strBuff.append("where MsgLS_Vcl_ID=? and MsgLS_StatTime=? ");
						strBuff.append("group by MsgLS_Vcl_ID");
						strBuff.append(")+");
						strBuff.append("MsgLSL_tLoadGPSDistance ");
						
						strBuff.append("where MsgLSL_Vcl_ID=? ");
						baseDAO.execUpdate(strBuff.toString(), new Object[]{lastTimes[1],
							MapGetter.getString(vclInfoMap, "VehicleID"),statDate,
							MapGetter.getString(vclInfoMap, "VehicleID"),statDate,
							MapGetter.getString(vclInfoMap, "VehicleID"),statDate,
							MapGetter.getString(vclInfoMap, "VehicleID"),statDate,
							MapGetter.getString(vclInfoMap, "VehicleID"),statDate,
							MapGetter.getString(vclInfoMap, "VehicleID"),statDate,
							MapGetter.getString(vclInfoMap, "VehicleID")});
					}else{
						strBuff.append("insert into Msg_LoadStatLast(MsgLSL_Vcl_ID,MsgLSL_PreTime,MsgLSL_tLoad,MsgLSL_tLoadRunKmExact,MsgLSL_tLoadRunKm,MsgLSL_tLoadRunKmECU,MsgLSL_tLoadMeterDistance,MsgLSL_tLoadGPSDistance) ");						
						strBuff.append("select ?,?,* from (select sum(MsgLS_AvgLoad*MsgLS_SecKm/1000) tLoad ,sum(MsgLS_AvgLoad*MsgLS_SecRunKmExact/1000) tLoadRunKmExact,sum(MsgLS_AvgLoad*MsgLS_SecRunKm/1000) tLoadRunKm	");					
						strBuff.append(",sum(MsgLS_AvgLoad*MsgLS_SecRunKmECU/1000) tLoadRunKmECU,sum(MsgLS_AvgLoad*MsgLS_SecMeterDistance/1000) tLoadMeterDistance ,sum(MsgLS_AvgLoad*MsgLS_SecGPSDistance/1000) tLoadGPSDistance from Msg_LoadStat where MsgLS_Vcl_ID = ? and MsgLS_StatTime = ? )tmp ");
						baseDAO.execInsert(strBuff.toString(), new Object[]{
							MapGetter.getString(vclInfoMap, "VehicleID"),lastTimes[1],
							MapGetter.getString(vclInfoMap, "VehicleID"),statDate});
					}
				}
			}
		}
	}
	/**获取一个载重段的开始时间、结束时间*/
	private String[] getTimeDefOfOneLoadLine(
			List<Map<String, Object>> loadSrcList) {
		return ListUtil.get(loadSrcList, "msgTime");
	}
	/**查询定时信息*/
	private List<Map<String, Object>> getTimingMsgOfOneVcl(
			Map<String, Object> vclInfoMap, String bgnTime, String endTime) {
		String agrNo = MapGetter.getString(vclInfoMap,"Tmnl_SoftEdition").toLowerCase();
		
		String termJPPSoft =  EquipVersionCommon.getSoftVerByAgrType("LAVcl_JPP").toLowerCase();
		String termPPSoft =  EquipVersionCommon.getSoftVerByAgrType("LAVcl_PP").toLowerCase();
		
		if(!StringUtil.isValid(agrNo)){
			return null;
		}
		StringBuffer sb =new StringBuffer();
		sb.append("select MsgT_ID,MsgT_vcl_id,MsgT_MsgTime as msgTime,MsgT_tWorkTime_UDS as runTime,msgt_vclSpeed as vclSpeed,ISNULL(MsgT_Load_UDS,0) as load,ifDisPoint=Case when msgt_vclSpeed=0  OR msgt_vclSpeed IS null or msgt_egnState=0 or msgt_egnState IS null then 1 else 0 end, ");
		if(termPPSoft.contains(agrNo))//412 PP
			sb.append("MsgT_tOilCons_UDS as oilCons,runKm=MsgT_tRunKm_UDS, '0.0' as MsgT_tRunKm,'0.0' as MsgT_tRunKmExact,'0.0' as MsgT_tRunKmECU,'0.0' as MsgT_tRunKmExact_PGN,VclP_Tmileage ");	
		//JPP
		else if(termJPPSoft.contains(agrNo)){
			sb.append("MsgT_tOilCons as oilCons,runKm=case when MsgT_tRunKm is not null then MsgT_tRunKm when MsgT_tRunKm IS NULL and MsgT_tRunKmExact IS not null then MsgT_tRunKmExact when MsgT_tRunKm IS NULL and MsgT_tRunKmExact IS  null and MsgT_tRunKmECU IS not null then MsgT_tRunKmECU end," +
					"MsgT_tRunKm,MsgT_tRunKmExact,MsgT_tRunKmECU,MsgT_tRunKmExact_PGN,VclP_Tmileage ");
		}
		sb.append(" from ("+this.getLoadSql(MapGetter.getString(vclInfoMap, "VehicleID"),bgnTime,endTime)+") temp order by MsgT_MsgTime ");
		
		List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
		if(StringUtil.isValid(sb.toString())){
			 list=this.baseDAO.execQuery(sb.toString(), new Object[]{});
		}
		return list;
	}
	/**组织查询定时信息语句*/
	private String getLoadSql(String VehicleID, String startTime, String endTime) {
		String sql = "";
    	SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd"); 
    	try {
    		//日期格式	Tue Mar 03 00:00:00 CST 2009
    		Date start_date =  DateUtil.toDate(startTime, "yyyy-MM-dd");
    		Date end_date =DateUtil.toDate(endTime, "yyyy-MM-dd");
    		
    		//判断起始日期如果不带时间
    		if(startTime.length()<11){
    			startTime = startTime + " 00:00:00";
    		}
    		//判断截止日期如果不带时间
    		if(endTime.length()<11){
    			endTime = endTime + " 23:59:59";
    		}
    		
    		Calendar ca = Calendar.getInstance(); 
    		ca.setTime(start_date);
    		Calendar ca1 = Calendar.getInstance(); 
    		ca1.setTime(end_date);
    		
    		//循环所有天数
    		while (ca.getTime().getTime()<= ca1.getTime().getTime()) {
    			String date =  formatter.format(ca.getTime());
    			String tableB="Msg_Timing" + "_" + date;
    			String tableVcl="Vcl_Pstn_"+ date;
    			sql += "select MsgT_ID,MsgT_vcl_id,MsgT_MsgTime,MsgT_Load_UDS,MsgT_tOilCons_UDS,MsgT_tOilCons "
						+",MsgT_tWorkTime_UDS,MsgT_tRunKm_UDS,MsgT_tRunKm,MsgT_tRunKmExact,MsgT_tRunKmECU,MsgT_tRunKmExact_PGN,VclP_TMileage "
						+",msgt_vclSpeed,msgt_egnState,MsgT_EBPState_UDS "
						+" from CTY_Egn_B.dbo."+tableB+" inner join (select ISNULL(vp1.VclP_TMileage,0) as VclP_TMileage,VclP_MsgID from  cty_vcl.dbo."+tableVcl+" vp1 "
						+" inner join (SELECT MAX(VclP_ID) as id FROM   cty_vcl.dbo."+tableVcl+" group  by VclP_MsgID) vp2 on vp1.VclP_ID = vp2.id and VclP_MsgTp_ID=2 and VclP_Vcl_ID = '"+VehicleID+"') temp on temp.VclP_MsgID = MsgT_ID  "
						+" where msgt_Vcl_id="+VehicleID+" and MsgT_MsgTime>='"+startTime+"' and MsgT_MsgTime<='"+endTime+"' "
					    +" and MsgT_SysTI_ID<>4 ";
//					    "and EXISTS ( select VclP_MsgID from CTY_Vcl.dbo.Vcl_Pstn_"+date+" where MsgT_ID = VclP_MsgID and VclP_MsgTp_ID=2 and VclP_IsApply=1 )";
			sql += " union ";
    			ca.add(Calendar.DAY_OF_YEAR, 1);	
    		}
    		if(!sql.equals("")){
    			sql = sql.substring(0,sql.length()-6);
    		}
    		
    	} catch (ParseException e) {
    		System.out.println(" GetTimQuery " +
			" 方法:getLoadSql 执行:获取查询载重数据sql 拼接异常");
    	}
    	return sql;
	}
	/**获取载重设置信息*/
	private Map<String, Object> getAndDealLoadSetMap(String vehicleID) {
		String strSQL = "select * from Vcl_LoadInfo where VclLI_VclId=?";
		Map<String,Object> loadSetMap = baseDAO.execQueryOne(strSQL, new Object[]{vehicleID});
		Map<String,Object> setMap = new HashMap<String,Object>();
		String  VclLI_BgnNoLoad = MapGetter.getString(loadSetMap,"VclLI_BgnNoLoad");
		String  VclLI_EndNoLoad = MapGetter.getString(loadSetMap,"VclLI_EndNoLoad");
		String VclLI_BgnLoad =  MapGetter.getString(loadSetMap,"VclLI_BgnLoad");
		String VclLI_EndLoad =  MapGetter.getString(loadSetMap,"VclLI_EndLoad");
		String VclLI_BgnFullLoad = MapGetter.getString(loadSetMap,"VclLI_BgnFullLoad");
		String VclLI_EndFullLoad = MapGetter.getString(loadSetMap,"VclLI_EndFullLoad");
		String VclLI_BgnSpeFullLoad = MapGetter.getString(loadSetMap,"VclLI_BgnSpeFullLoad");
		String VclLI_EndSpeFullLoad = MapGetter.getString(loadSetMap,"VclLI_EndSpeFullLoad");
		String VclLI_BgnInvalid = MapGetter.getString(loadSetMap,"VclLI_BgnInvalid");
		String VclLI_EndInvalid = MapGetter.getString(loadSetMap,"VclLI_EndInvalid");
		/*String VclLI_RegMultiplier =  MapGetter.getString(loadSetMap,"VclLI_RegMultiplier");
		String VclLI_RegRemainder = MapGetter.getString(loadSetMap,"VclLI_RegRemainder");*/
		String VclLI_MMEType = MapGetter.getString(loadSetMap,"VclLI_MMEType");
		String VclLI_ParkInterval = MapGetter.getString(loadSetMap,"VclLI_ParkInterval");
		
		String VclLI_NoLoadRegM = MapGetter.getString(loadSetMap,"VclLI_NoLoadRegM");
		String VclLI_NoLoadRegR = MapGetter.getString(loadSetMap,"VclLI_NoLoadRegR");
		String VclLI_LoadRegM = MapGetter.getString(loadSetMap,"VclLI_LoadRegM");
		String VclLI_LoadRegR = MapGetter.getString(loadSetMap,"VclLI_LoadRegR");
		String VclLI_FullLoadRegM = MapGetter.getString(loadSetMap,"VclLI_FullLoadRegM");
		String VclLI_FullLoadRegR = MapGetter.getString(loadSetMap,"VclLI_FullLoadRegR");
		String VclLI_SpeFulLLoadRegM = MapGetter.getString(loadSetMap,"VclLI_SpeFulLLoadRegM");
		String VclLI_SpeFullLoadRegR = MapGetter.getString(loadSetMap,"VclLI_SpeFulLLoadRegR");
		String VclLI_CLRegM = MapGetter.getString(loadSetMap,"VclLI_CLRegM");
		String VclLI_CLRegR = MapGetter.getString(loadSetMap,"VclLI_CLRegR");
		String VclLI_ESARegM = MapGetter.getString(loadSetMap,"VclLI_ESARegM");
		String VclLI_ESARegR = MapGetter.getString(loadSetMap,"VclLI_ESARegR");
		String VclLI_HTGRegM = MapGetter.getString(loadSetMap,"VclLI_HTGRegM");
		String VclLI_HTGRegR = MapGetter.getString(loadSetMap,"VclLI_HTGRegR");
		String VclLI_OtherRegM = MapGetter.getString(loadSetMap,"VclLI_OtherRegM");
		String VclLI_OtherRegR = MapGetter.getString(loadSetMap,"VclLI_OtherRegR");
		String VclLI_FenRegSet = MapGetter.getString(loadSetMap,"VclLI_FenRegSet");

		
		if(StringUtil.isValid(VclLI_BgnNoLoad)){
			setMap.put("noLoadBgn",Double.parseDouble(VclLI_BgnNoLoad));
		}
		if(StringUtil.isValid(VclLI_EndNoLoad)){
			setMap.put("noLoadEnd",Double.parseDouble(VclLI_EndNoLoad));
		}
		if(StringUtil.isValid(VclLI_BgnLoad)){
			setMap.put("zhuangLoadBgn",Double.parseDouble(VclLI_BgnLoad));
		}
		if(StringUtil.isValid(VclLI_EndLoad)){
			setMap.put("zhuangLoadEnd",Double.parseDouble(VclLI_EndLoad));
		}
		if(StringUtil.isValid(VclLI_BgnFullLoad)){
			setMap.put("fullLoadBgn",Double.parseDouble(VclLI_BgnFullLoad));
		}
		if(StringUtil.isValid(VclLI_EndFullLoad)){
			setMap.put("fullLoadEnd",Double.parseDouble(VclLI_EndFullLoad));
		}
		if(StringUtil.isValid(VclLI_BgnSpeFullLoad)){
			setMap.put("teLoadBgn",Double.parseDouble(VclLI_BgnSpeFullLoad));
		}
		if(StringUtil.isValid(VclLI_EndSpeFullLoad)){
			setMap.put("teLoadEnd",Double.parseDouble(VclLI_EndSpeFullLoad));
		}
		//无效范围都设定
		if(StringUtil.isValid(VclLI_BgnInvalid)&&StringUtil.isValid(VclLI_EndInvalid)){
			if(Double.parseDouble(VclLI_BgnInvalid)>Double.parseDouble(VclLI_EndInvalid)){
				setMap.put("invalidBgn",Double.parseDouble(VclLI_EndInvalid));
				setMap.put("invalidEnd",Double.parseDouble(VclLI_BgnInvalid));
			}else{
				setMap.put("invalidBgn",Double.parseDouble(VclLI_BgnInvalid));
				setMap.put("invalidEnd",Double.parseDouble(VclLI_EndInvalid));
			}
			//无效范围，有开始值，无结束值
		}else if(StringUtil.isValid(VclLI_BgnInvalid)&&!(StringUtil.isValid(VclLI_EndInvalid))){
			setMap.put("invalidBgn",0);
			setMap.put("invalidEnd",Double.parseDouble(VclLI_BgnInvalid));
			//无效范围，无开始值，有结束值
		}else if(!(StringUtil.isValid(VclLI_BgnInvalid))&&StringUtil.isValid(VclLI_EndInvalid)){
			setMap.put("invalidBgn",0);
			setMap.put("invalidEnd",Double.parseDouble(VclLI_EndInvalid));
		}else{//未设定无效范围
			setMap.put("invalidBgn",-1);
			setMap.put("invalidEnd",-1);
		}
		
		/*if(StringUtil.isValid(VclLI_RegMultiplier)){
			setMap.put("x",Double.parseDouble(VclLI_RegMultiplier));
		}
		if(StringUtil.isValid(VclLI_RegRemainder)){
			setMap.put("y",Double.parseDouble(VclLI_RegRemainder));
		}*/
		setMap.put("x",(double)1);
		setMap.put("y",(double)0);
		
		if(StringUtil.isValid(VclLI_MMEType)){
			setMap.put("MMEType",Integer.parseInt(VclLI_MMEType));
		}
		if(StringUtil.isValid(VclLI_ParkInterval)){
			setMap.put("MME_IntervalMin",Integer.parseInt(VclLI_ParkInterval));
		}
		
		if(StringUtil.isValid(VclLI_NoLoadRegM)){
			setMap.put("NoLoadRegM",Double.parseDouble(VclLI_NoLoadRegM));
		}
		if(StringUtil.isValid(VclLI_NoLoadRegR)){
			setMap.put("NoLoadRegR",Double.parseDouble(VclLI_NoLoadRegR));
		}
		if(StringUtil.isValid(VclLI_LoadRegM)){
			setMap.put("LoadRegM",Double.parseDouble(VclLI_LoadRegM));
		}
		if(StringUtil.isValid(VclLI_LoadRegR)){
			setMap.put("LoadRegR",Double.parseDouble(VclLI_LoadRegR));
		}
		if(StringUtil.isValid(VclLI_FullLoadRegM)){
			setMap.put("FullLoadRegM",Double.parseDouble(VclLI_FullLoadRegM));
		}
		if(StringUtil.isValid(VclLI_FullLoadRegR)){
			setMap.put("FullLoadRegR",Double.parseDouble(VclLI_FullLoadRegR));
		}
		if(StringUtil.isValid(VclLI_SpeFulLLoadRegM)){
			setMap.put("SpeFullLoadRegM",Double.parseDouble(VclLI_SpeFulLLoadRegM));
		}
		if(StringUtil.isValid(VclLI_SpeFullLoadRegR)){
			setMap.put("SpeFullLoadRegR",Double.parseDouble(VclLI_SpeFullLoadRegR));
		}
		if(StringUtil.isValid(VclLI_CLRegM)){
			setMap.put("CLRegM",Double.parseDouble(VclLI_CLRegM));
		}
		if(StringUtil.isValid(VclLI_CLRegR)){
			setMap.put("CLRegR",Double.parseDouble(VclLI_CLRegR));
		}
		if(StringUtil.isValid(VclLI_ESARegM)){
			setMap.put("ESARegM",Double.parseDouble(VclLI_ESARegM));
		}
		if(StringUtil.isValid(VclLI_ESARegR)){
			setMap.put("ESARegR",Double.parseDouble(VclLI_ESARegR));
		}
		if(StringUtil.isValid(VclLI_HTGRegM)){
			setMap.put("HTGRegM",Double.parseDouble(VclLI_HTGRegM));
		}
		if(StringUtil.isValid(VclLI_HTGRegR)){
			setMap.put("HTGRegR",Double.parseDouble(VclLI_HTGRegR));
		}
		if(StringUtil.isValid(VclLI_OtherRegM)){
			setMap.put("OtherRegM",Double.parseDouble(VclLI_OtherRegM));
		}
		if(StringUtil.isValid(VclLI_OtherRegR)){
			setMap.put("OtherRegR",Double.parseDouble(VclLI_OtherRegR));
		}
		if(StringUtil.isValid(VclLI_FenRegSet)){
			setMap.put("FenRegSet",VclLI_FenRegSet);
		}
		return setMap;
	
	}
	/**
	 * 获取有效设备
	 * @return
	 */
	public List<Map<String,Object>> getVclInfoList(){
		String strSQL = "select * from V_VehicleInfo " +
				"where UsefulLife>=GETDATE() and Tmnl_SoftEdition is not null and Tmnl_SoftEdition!='' ";
		//通过协议类型获取软件版本号
		String termJPPSoft =  EquipVersionCommon.getSoftVerByAgrType("LAVcl_JPP");
		String termPPSoft =  EquipVersionCommon.getSoftVerByAgrType("LAVcl_PP");
		StringBuffer termSoft = new StringBuffer(termJPPSoft);
		if(StringUtil.isNullOrEmpty(termPPSoft)){
			if(StringUtil.isNullOrEmpty(termSoft.toString()))termSoft.append(",");
			termSoft.append(termPPSoft);
		}
		strSQL+="and Tmnl_SoftEdition in ("+termSoft.toString()+") ";
		List<Map<String,Object>> vclInfoList = baseDAO.execQuery(strSQL, new Object[]{});
		return vclInfoList;
	}
	
	/**
	 * 统计逻辑
	 * @param vclInfoMap
	 * @return 
	 * 		0：昨日设备无定时信息
	 * 		1：统计成功
	 * 		2：统计失败
	 * 更新历史：2013-10-25 jiyongtian去掉，更改为最新的逻辑
	 */
/*	public int statLogic(Map<String,Object> vclInfoMap){
		
		//通过设备Id获取设备的载重范围
		Map<String,Object> loadSetMap = this.getVclLoadScope(MapGetter.getString(vclInfoMap, "VehicleID"));
		if(loadSetMap.isEmpty())return 3;//未设置载重范围，不进行统计返回失败
		
		float loadLow = this.getFloat(loadSetMap, "loadLow");//载重下限
		float loadUpper = this.getFloat(loadSetMap, "loadUpper");//载重上限
		float loadValidB = this.getFloat(loadSetMap, "loadValidB");//无效载重下限
		float loadValidE = this.getFloat(loadSetMap, "loadValidE");//无效载重上限
		float regMultiplier = this.getFloat(loadSetMap, "regMultiplier");//载重调整公式（被乘数）
		float regRemainder = this.getFloat(loadSetMap, "regRemainder");//载重调整公式（余数）
		
		
		//统计日期
		String statDate = DateUtil.addDay(-1);
		//获取昨日设备的定时信息
		List<Map<String,Object>> timingInfoList = this.getTimingInfoList(MapGetter.getString(vclInfoMap, "VehicleID"), 
				MapGetter.getString(vclInfoMap, "Tmnl_SoftEdition"), statDate, statDate+" 23:59:59");
		if(timingInfoList==null||timingInfoList.size()<=0)return 0;
		Map<String,Object> tmpMap = null;//临时对象
		Map<String,Object> preMap = null;
		List<String> sqlList = new ArrayList<String>();//执行SQL集合
		List<Object[]> paramList = new ArrayList<Object[]>();//执行SQL参数集合
		double tmpLoad = 0;//临时载重量
		float tmpTRunKm = 0;//临时ECM累计里程
		float tmpTOilCons = 0;//临时累计油耗
		float tmpTWorkTime = 0;//临时工作小时数
		int tmpRow = 0;
		int timingInfoListLen = timingInfoList.size();
		String preTime = "";
		
		for(int i = 0;i<timingInfoListLen;i++){
			Map<String,Object> timingInfoMap = timingInfoList.get(i);
			//累加载重量；累加载重量有效记录数
			if(StringUtil.isNullOrEmpty(MapGetter.getString(timingInfoMap, "MsgT_Load_UDS"))){
				try{
					float tarLoad = Float.parseFloat(MapGetter.getString(timingInfoMap, "MsgT_Load_UDS"));
					//jiyongtian20130406有效数据：在有效档位内，同时不在无效档位内
					if(loadValidB > 0 || loadValidE > 0){
						if(loadLow<=tarLoad&&tarLoad<=loadUpper&&(tarLoad<loadValidB||tarLoad>loadValidE)){
							tmpLoad = NumberFormat.add(tmpLoad, this.getFloat(timingInfoMap, "MsgT_Load_UDS"));
							tmpRow++;
						}
					}else{
						if(loadLow<=tarLoad&&tarLoad<=loadUpper){
							tmpLoad = NumberFormat.add(tmpLoad, this.getFloat(timingInfoMap, "MsgT_Load_UDS"));
							tmpRow++;
						}
					}
					//end
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			
			//当前ECM累计里程，用来获取不为空的数据
			if(StringUtil.isNullOrEmpty(MapGetter.getString(timingInfoMap, "tRunKm")))tmpTRunKm = this.getFloat(timingInfoMap, "tRunKm");
			
			//当前累计油耗，用来获取不为空的数据
			if(StringUtil.isNullOrEmpty(MapGetter.getString(timingInfoMap, "tOilCons")))tmpTOilCons = this.getFloat(timingInfoMap, "tOilCons");
			
			//当前累计工作时间，用来获取不为空的数据
			if(StringUtil.isNullOrEmpty(MapGetter.getString(timingInfoMap, "tWorkTime")))tmpTWorkTime = this.getFloat(timingInfoMap, "tWorkTime");
			
			
			//临时对象不为空，则进行验证属性值是否有效，无效则重新赋值
			if(tmpMap!=null&&!tmpMap.isEmpty()){
				
				//里程
				if(!StringUtil.isNullOrEmpty(MapGetter.getString(tmpMap, "tRunKm"))){
					tmpMap.put("tRunKm", MapGetter.getString(timingInfoMap, "tRunKm"));
				}
				//油耗
				if(!StringUtil.isNullOrEmpty(MapGetter.getString(tmpMap, "tOilCons"))){
					tmpMap.put("tOilCons", MapGetter.getString(timingInfoMap, "tOilCons"));
				}
				//工作小时
				if(!StringUtil.isNullOrEmpty(MapGetter.getString(tmpMap, "tWorkTime"))){
					tmpMap.put("tWorkTime", MapGetter.getString(timingInfoMap, "tWorkTime"));
				}
				
			}
			
			if(MapGetter.getString(timingInfoMap, "MsgT_EgnState").equals("0")
					||this.getFloat(timingInfoMap, "MsgT_VclSpeed")==0){
				double avgLoad = 0;
				double tRunKm = 0;
				double tOilCons=0;
				double tWorkTime = 0;
				if(tmpMap!=null&&!tmpMap.isEmpty()){
					if(tmpRow>0){
						//区间平均载重
						avgLoad = NumberFormat.div(tmpLoad, tmpRow);
						//区间ECM里程
						tRunKm = NumberFormat.sub(tmpTRunKm, this.getFloat(tmpMap, "tRunKm"));
						//区间油耗
						tOilCons = NumberFormat.sub(tmpTOilCons, this.getFloat(tmpMap, "tOilCons"));
						//区间工作小时
						tWorkTime = NumberFormat.sub(tmpTWorkTime, this.getFloat(tmpMap, "tWorkTime"));
						//执行SQL集合
						sqlList.add("insert into Msg_LoadStat (MsgLS_Vcl_ID,MsgLS_AvgLoad,MsgLS_SecKm,MsgLS_SecOilCon,MsgLS_SecTimeH," +
								"MsgLS_BgnTime,MsgLS_EndTime,MsgLS_StatTime)values(?,?,?,?,?,?,?,?);");
						//执行SQL参数集合
						paramList.add(new Object[]{MapGetter.getString(vclInfoMap, "VehicleID"),handlerLoad(avgLoad,regMultiplier,regRemainder),handlerNeg(tRunKm),handlerNeg(tOilCons),handlerNeg(tWorkTime),
								MapGetter.getString(tmpMap, "MsgT_MsgTime"),MapGetter.getString(timingInfoMap, "MsgT_MsgTime"),statDate});
					}	
				}else{//此次统计序列中第一个分割点
					
					//检索上次统计结束时间
					preMap = this.getPreTime(MapGetter.getString(vclInfoMap, "VehicleID"));
					if(preMap!=null&&!preMap.isEmpty()){
						
						String preStatDate = MapGetter.getString(preMap, "MsgLSL_PreTime");
						//查询序列修改为上次统计的最后一个分割点到此次统计的第一个分割点
						List<Map<String,Object>> preList = this.getTimingInfoList(MapGetter.getString(vclInfoMap, "VehicleID"),MapGetter.getString(vclInfoMap, "Tmnl_SoftEdition"), preStatDate, MapGetter.getString(timingInfoMap, "MsgT_MsgTime"));
						if(preList!=null&&preList.size()>0){//正常情况下preList.size()>=2 一定包含上次统计的最后一个分割点和这次统计的第一个分割点
							double preTmpLoad = 0;
							double preTmpTRunKm = -1;
							double preTmpOilCons = -1;
							double preTmpWorkTime = -1;
							double nowTmpTRunKm = 0;
							double nowTmpOilCons = 0;
							double nowTmpWorkTime = 0;
							int preTmpRow = 0;
							for(Map<String,Object> pre:preList){
								if(StringUtil.isNullOrEmpty(MapGetter.getString(pre, "MsgT_Load_UDS"))){
									try{
										float tarLoad = Float.parseFloat(MapGetter.getString(pre, "MsgT_Load_UDS"));
										//jiyongtian 增加无效区间校验
										if((loadValidB > 0) ||(loadValidE > 0)){
											if(loadLow<=tarLoad&&tarLoad<=loadUpper&&(tarLoad<loadValidB||tarLoad>loadValidE)){
												preTmpLoad = NumberFormat.add(preTmpLoad, tarLoad);
												preTmpRow++;
											}else{
												
											}	
										}else{
											if(loadLow<=tarLoad&&tarLoad<=loadUpper){
												preTmpLoad = NumberFormat.add(preTmpLoad, tarLoad);
												preTmpRow++;
											}else{
												
											}
										}
										
									}catch(Exception e){
										e.printStackTrace();
									}
								}
								if(preTmpTRunKm==-1){
									if(StringUtil.isNullOrEmpty(MapGetter.getString(pre, "tRunKm")))
										preTmpTRunKm = this.getFloat(pre, "tRunKm");
								}
								if(preTmpOilCons==-1){
									if(StringUtil.isNullOrEmpty(MapGetter.getString(pre, "tOilCons")))
										preTmpOilCons = this.getFloat(pre, "tOilCons");
								}
								if(preTmpWorkTime==-1){
									if(StringUtil.isNullOrEmpty(MapGetter.getString(pre, "tWorkTime")))
										preTmpWorkTime = this.getFloat(pre, "tWorkTime");
								}
								if(StringUtil.isNullOrEmpty(MapGetter.getString(pre, "tRunKm")))
									nowTmpTRunKm = this.getFloat(pre, "tRunKm");
								if(StringUtil.isNullOrEmpty(MapGetter.getString(pre, "tOilCons")))
									nowTmpOilCons = this.getFloat(pre, "tOilCons");
								if(StringUtil.isNullOrEmpty(MapGetter.getString(pre, "tWorkTime")))
									nowTmpWorkTime = this.getFloat(pre, "tWorkTime");
								
							}
							if(preTmpRow>0){//此区间有有效的载重值
								//区间平均载重
								avgLoad = NumberFormat.div(preTmpLoad, preTmpRow);
								//区间ECM里程
								tRunKm = NumberFormat.sub(nowTmpTRunKm, preTmpTRunKm);
								//区间油耗
								tOilCons = NumberFormat.sub(nowTmpOilCons, preTmpOilCons);
								//区间工作小时
								tWorkTime = NumberFormat.sub(nowTmpWorkTime, preTmpWorkTime);

								//执行SQL集合
								sqlList.add("insert into Msg_LoadStat (MsgLS_Vcl_ID,MsgLS_AvgLoad,MsgLS_SecKm,MsgLS_SecOilCon,MsgLS_SecTimeH,MsgLS_BgnTime," +
										"MsgLS_EndTime,MsgLS_StatTime)values(?,?,?,?,?,?,?,?);");
								//执行SQL参数集合
								paramList.add(new Object[]{MapGetter.getString(vclInfoMap, "VehicleID"),handlerLoad(avgLoad,regMultiplier,regRemainder),handlerNeg(tRunKm),handlerNeg(tOilCons),handlerNeg(tWorkTime),
										preStatDate,MapGetter.getString(timingInfoMap, "MsgT_MsgTime"),statDate});

							}else{//此区间没有有效的载重值
								
							}						
						}
					}
					
				}
				//临时变量初始化
				tmpMap = timingInfoMap;
				tmpRow = 0;
				tmpLoad = 0;
			}
			
			//遍历到最后一条数据
			if(i==timingInfoListLen-1){
				if(tmpMap!=null){
					preTime = MapGetter.getString(tmpMap, "MsgT_MsgTime");
				}
			}
			
		}
		
		int iFlag = 3;
		StringBuffer strBuff = new StringBuffer();
		//操作载重负荷统计表
		if(sqlList.size()>0&&paramList.size()>0){
			boolean flag = tranDAO.batch(sqlList, paramList);
			//插入成功，则向Msg_LoadStatLast插入数据
			int i = 0;
			if(flag){
				if(preMap==null||preMap.isEmpty()){
					strBuff.append("insert into Msg_LoadStatLast(MsgLSL_Vcl_ID,MsgLSL_PreTime,MsgLSL_tLoad) ");
					strBuff.append("select ?,?,tLoad from (select sum(MsgLS_AvgLoad*MsgLS_SecKm/1000) tLoad from Msg_LoadStat ");
					strBuff.append("where MsgLS_Vcl_ID=? and MsgLS_StatTime=? ");
					strBuff.append("group by MsgLS_Vcl_ID) tmp");
					i = baseDAO.execInsert(strBuff.toString(), new Object[]{MapGetter.getString(vclInfoMap, "VehicleID"),preTime,MapGetter.getString(vclInfoMap, "VehicleID"),statDate});
				}else{
					strBuff.append("update Msg_LoadStatLast set MsgLSL_PreTime=?,");
					strBuff.append("MsgLSL_tLoad=( ");
					strBuff.append("select sum(MsgLS_AvgLoad*MsgLS_SecKm/1000) tLoad from Msg_LoadStat ");
					strBuff.append("where MsgLS_Vcl_ID=? and MsgLS_StatTime=? ");
					strBuff.append("group by MsgLS_Vcl_ID");
					strBuff.append(")+");
					strBuff.append("MsgLSL_tLoad ");
					strBuff.append("where MsgLSL_Vcl_ID=? ");
					i = baseDAO.execUpdate(strBuff.toString(), new Object[]{preTime,MapGetter.getString(vclInfoMap, "VehicleID"),statDate,MapGetter.getString(vclInfoMap, "VehicleID")});
				}
				if(i>0){
					iFlag = 1;
				}else{
					iFlag = 2;
				}
			}else{
				iFlag = 2;
			}
		}
		
		return iFlag;
	}
*/	/**
	 * 获取设备定时信息
	 * @param vclId
	 * @param softVer
	 * @param bgnTime
	 * @param endTime
	 * @return
	 */
/*	public List<Map<String,Object>> getTimingInfoList(String vclId,String softVer,String bgnTime,String endTime){
		StringBuffer strBuff = new StringBuffer();
		String agrNo = EquipVersionCommon.getAgrNoBySoftVer(softVer);
		for(int i = 0;;i++){
			if(DateUtil.toDate(DateUtil.addDay(bgnTime, i), "yyyy-MM-dd").getTime()
					>DateUtil.toDate(endTime, "yyyy-MM-dd").getTime()){
				break;
			}
			String tableDateName = DateUtil.addDay(bgnTime, i).replace("-", "");
			if(!strBuff.toString().equals(""))strBuff.append(" union all ");
			if("412".equals(agrNo)){
				strBuff.append("select *,MsgT_tWorkTime_UDS tWorkTime,MsgT_tOilCons_UDS tOilCons,MsgT_tRunKm_UDS tRunKm " +
						"from CTY_Egn_B.dbo.Msg_Timing_"+tableDateName+" where MsgT_Vcl_ID="+vclId+" ");
			}else if("413".equals(agrNo)||"414".equals(agrNo)||"418".equals(agrNo)||"420".equals(agrNo)){
				strBuff.append("select *,MsgT_tWorkTime_UDS tWorkTime,MsgT_tOilCons tOilCons,tRunKm=case when MsgT_tRunKm is not null then MsgT_tRunKm " +
						"when MsgT_tRunKm is null and MsgT_tRunKmExact is not null then MsgT_tRunKmExact " +
						"else MsgT_tRunKmECU end from CTY_Egn_B.dbo.Msg_Timing_"+tableDateName+" where MsgT_Vcl_ID="+vclId+" ");
			}else{
				//其他版本号暂不处理
				return null;
			}
		}
		strBuff.append("and MsgT_MsgTime>='"+bgnTime+"' and MsgT_MsgTime<='"+endTime+"' ");
		strBuff.append("and MsgT_SysTI_ID!=4 ");//关机固定间隔信息除外
		List<Map<String,Object>> timingInfoList = null;
		if(strBuff.indexOf("select")>=0)timingInfoList = baseDAO.execQuery(strBuff.toString(), new Object[]{});
		return timingInfoList;
	}
*/	
	/**
	 * 设备的上次统计结束信息
	 * @param vclId
	 * @return
	 */
	public Map<String,Object> getPreTime(String vclId){
		String strSQL = "select top 1 * from Msg_LoadStatLast where MsgLSL_Vcl_ID=? ";
		Map<String,Object> preMap = baseDAO.execQueryOne(strSQL, new Object[]{vclId});
		return preMap;
	}
	
/*	public float getFloat(Map<String,Object> map,String key){
		try{
			if(StringUtil.isNullOrEmpty(MapGetter.getString(map, key)))
				return Float.parseFloat(MapGetter.getString(map, key));
		}catch(Exception e){}
		return 0;
	}
	
	public double handlerNeg(double value){
		if(value<0)value = 0;
		return value;
	}
	
	public double handlerLoad(double load,double regMultiplier,double regRemainder){
		load = NumberFormat.mul(load, regMultiplier)+regRemainder;
		if(load<0)load = 0;
		return load;
	}
	
*/	/**
	 * 通过设备Id获取设备的载重范围及载重调整量
	 * @param vclId
	 * @return
	 */
/*	public Map<String,Object> getVclLoadScope(String vclId){
		//载重范围下限值
		String scopeLowSql = "select MIN(tmp.VclLI_BgnNoLoad)scopeLow from " +
				"(select VclLI_BgnNoLoad from Vcl_LoadInfo where VclLI_VclId=? " +
				"union select VclLI_BgnLoad from Vcl_LoadInfo where VclLI_VclId=? " +
				"union select VclLI_BgnFullLoad from Vcl_LoadInfo where VclLI_VclId=? " +
				"union select VclLI_BgnSpeFullLoad from Vcl_LoadInfo where VclLI_VclId=?" +
				")tmp";
		Map<String,Object> scopeLowMap = baseDAO.execQueryOne(scopeLowSql, new Object[]{vclId,vclId,vclId,vclId});
		
		//载重范围上限值
		String scopeUpperSql = "select MAX(tmp.VclLI_EndNoLoad)scopeUpper from " +
				"(select VclLI_EndNoLoad from Vcl_LoadInfo where VclLI_VclId=? " +
				"union select VclLI_EndLoad from Vcl_LoadInfo where VclLI_VclId=? " +
				"union select VclLI_EndFullLoad from Vcl_LoadInfo where VclLI_VclId=? " +
				"union select VclLI_EndSpeFullLoad from Vcl_LoadInfo where VclLI_VclId=?" +
				")tmp";
		Map<String,Object> scopeUpperMap = baseDAO.execQueryOne(scopeUpperSql, new Object[]{vclId,vclId,vclId,vclId});
		
		//载重无效范围及载重调整量
		String loadSQL = "select * from Vcl_LoadInfo where VclLI_VclId=?;";
		Map<String,Object> loadMap = baseDAO.execQueryOne(loadSQL, new Object[]{vclId});
		
		Map<String,Object> retMap = new HashMap<String,Object>();
		float loadLow = 0;
		float loadUpper = 0;
		float loadValidB = 0;
		float loadValidE = 0;
		float regMultiplier = 1;
		float regRemainder = 0;
		if(!loadMap.isEmpty()){
			if(StringUtil.isNullOrEmpty(MapGetter.getString(scopeLowMap, "scopeLow"))){
				try{
					loadLow = Float.parseFloat(MapGetter.getString(scopeLowMap, "scopeLow"));
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			
			if(StringUtil.isNullOrEmpty(MapGetter.getString(scopeUpperMap, "scopeUpper"))){
				try{
					loadUpper = Float.parseFloat(MapGetter.getString(scopeUpperMap, "scopeUpper"));
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			
			if(StringUtil.isValid(MapGetter.getString(loadMap,"VclLI_BgnInvalid"))){
				try{
					loadValidB = Float.parseFloat(MapGetter.getString(loadMap,"VclLI_BgnInvalid"));
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			
			if(StringUtil.isValid(MapGetter.getString(loadMap,"VclLI_EndInvalid"))){
				try{
					loadValidE = Float.parseFloat(MapGetter.getString(loadMap,"VclLI_EndInvalid"));
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			
			if(StringUtil.isValid(MapGetter.getString(loadMap,"VclLI_RegMultiplier"))){
				try{
					regMultiplier = Float.parseFloat(MapGetter.getString(loadMap,"VclLI_RegMultiplier"));
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			
			if(StringUtil.isValid(MapGetter.getString(loadMap,"VclLI_RegRemainder"))){
				try{
					regRemainder = Float.parseFloat(MapGetter.getString(loadMap,"VclLI_RegRemainder"));
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			
			if(loadValidB>loadValidE){
				float temp = loadValidE;
				loadValidE = loadValidB;
				loadValidB = temp;
			}
			retMap.put("loadLow", loadLow);
			retMap.put("loadUpper", loadUpper);
			retMap.put("loadValidB", loadValidB);
			retMap.put("loadValidE", loadValidE);
			retMap.put("regMultiplier", regMultiplier);
			retMap.put("regRemainder", regRemainder);
		}
		
		return retMap;
	}*/
	
	public List<Map<String, Object>> getPstnDataOfStopTiming(String vehicleID,
			String startTime, String endTime) {
		
		StringBuffer strBuf = new StringBuffer();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd"); 
    	try {
    		Date start_date =  DateUtil.toDate(startTime, "yyyy-MM-dd");
    		Date end_date =DateUtil.toDate(endTime, "yyyy-MM-dd");
    		
    		if(startTime.length()<11){
    			startTime = startTime + " 00:00:00";
    		}
    		if(endTime.length()<11){
    			endTime = endTime + " 23:59:59";
    		}
    		
    		Calendar ca = Calendar.getInstance(); 
    		ca.setTime(start_date);
    		Calendar ca1 = Calendar.getInstance(); 
    		ca1.setTime(end_date);
    		
    		String date = "";
//    		int i=0;
    		while (ca.getTime().getTime()<= ca1.getTime().getTime()) {
    			date =  formatter.format(ca.getTime());
    			/*if(i==0){
    				strBuf.append("SELECT top 1 MsgT_ID,MsgT_Vcl_ID,MsgT_MsgTime,");
        			strBuf.append("lat = (select top 1 VclP_La from CTY_Vcl.dbo.Vcl_Pstn_" + date+" where MsgT_ID = VclP_MsgID AND VclP_MsgTp_ID = 2 and VclP_La is not null and VclP_Lo is not null and VclP_La >0 and VclP_Lo>0 order by VclP_PstnTime),");
        			strBuf.append("lng = (select top 1 VclP_Lo from CTY_Vcl.dbo.Vcl_Pstn_" + date+" where MsgT_ID = VclP_MsgID AND VclP_MsgTp_ID = 2 and VclP_La is not null and VclP_Lo is not null and VclP_La >0 and VclP_Lo>0 order by VclP_PstnTime) ");
        			strBuf.append("from CTY_Egn_B.dbo.Msg_Timing_"+date+" WHERE  MsgT_Vcl_ID = '"+vehicleID+"' and MsgT_SysTI_ID<>4 ");
        			strBuf.append("and exists (select VclP_ID from CTY_Vcl.dbo.Vcl_Pstn_"+date+" where VclP_MsgID = MsgT_ID and VclP_Vcl_ID = MsgT_Vcl_ID and  VclP_MsgTp_ID = 2)  ");
        			strBuf.append("union ");
    			}*/
    			/*strBuf.append("SELECT MsgT_ID,MsgT_Vcl_ID,MsgT_MsgTime,");
    			strBuf.append("lat = (select top 1 VclP_La from CTY_Vcl.dbo.Vcl_Pstn_" + date+" where MsgT_ID = VclP_MsgID AND VclP_Vcl_ID="+vehicleID+" AND VclP_MsgTp_ID = 2 and VclP_La is not null and VclP_Lo is not null and VclP_La >0 and VclP_Lo>0 order by VclP_PstnTime),");
    			strBuf.append("lng = (select top 1 VclP_Lo from CTY_Vcl.dbo.Vcl_Pstn_" + date+" where MsgT_ID = VclP_MsgID AND VclP_Vcl_ID="+vehicleID+" AND VclP_MsgTp_ID = 2 and VclP_La is not null and VclP_Lo is not null and VclP_La >0 and VclP_Lo>0 order by VclP_PstnTime) ");
    			strBuf.append("from CTY_Egn_B.dbo.Msg_Timing_"+date+" WHERE  MsgT_Vcl_ID = '"+vehicleID+"' and (MsgT_VclSpeed = 0 or MsgT_VclSpeed is null) ");
    			strBuf.append("and MsgT_MsgTime between '"+startTime+"' and '"+endTime+"' and MsgT_SysTI_ID<>4  ");
    			strBuf.append("and exists (select VclP_ID from CTY_Vcl.dbo.Vcl_Pstn_"+date+" where VclP_MsgID = MsgT_ID and VclP_Vcl_ID = MsgT_Vcl_ID and  VclP_MsgTp_ID = 2)  ");
    			strBuf.append(" union ");*/
    			//jinjiayu   20150328 上面的sql执行慢
    			strBuf.append(" select msgt_id,MsgT_MsgTime,VclP_Lo lng,VclP_La lat,ROW_NUMBER() over(partition by msgt_id order by vclp_pstntime) ord");
    			strBuf.append(" from cty_egn_b.dbo.msg_timing_"+date+" inner join cty_vcl.dbo.vcl_pstn_"+date+" on MsgT_ID = VclP_MsgID");
    			strBuf.append(" where msgt_vcl_id = '"+vehicleID+"' AND vclp_msgtp_id = 2");
    			strBuf.append(" AND (msgt_vclspeed = 0 OR msgt_vclspeed IS NULL ) AND msgt_systi_id <> 4 AND vclp_la IS NOT NULL");
    			strBuf.append(" AND vclp_lo IS NOT NULL AND vclp_la > 0 AND vclp_lo > 0 and MsgT_MsgTime between '"+startTime+"' and '"+endTime+"'");
    			strBuf.append(" union ");
    			ca.add(Calendar.DAY_OF_YEAR, 1);
//    			i++;
    		}
    	} catch (ParseException e) {
    		
    	}
    	if(strBuf.toString().length()>0){
    		String sql = "select MsgT_ID,MsgT_MsgTime as msgTime,lng,lat from (";
    		sql += strBuf.toString().substring(0, strBuf.toString().length()-6);
    		sql += " ) temp where 1=1 and ord = 1 order by MsgT_MsgTime ";
    		return baseDAO.execQuery(sql, new Object[]{});
    	}else{
    		return null;
    	}
	}
	
	 /**
		 * 根据设备所属组织机构获取该组织机构及其上级 围栏【类型】属性为是且围栏为圆形的数据集合，按创建（修改）日期排序
		 * 
		 * @param Map<String,Object> vclInfo
		 * 
		 * @return
		 */
		public List<Map<String,Object>> getEnclosureByVclDBCodeAndAbove(Map<String,Object> vclInfo){
			String DBCode = MapGetter.getString(vclInfo,"DBCode");
			if(StringUtil.isValid(DBCode)){
				String[] dbPart = DBCode.split("D");
				DBCode = "";
				for(int i=0;i<dbPart.length;i++){
					if(i==0){
						DBCode = "'"+dbPart[i]+"'";
					}else{
						DBCode += ",'";
						for(int j=0;j<=i;j++){
							if(j==0){
								DBCode += dbPart[j];
							}else{
								DBCode += "D"+dbPart[j];
							}
						}
						DBCode += "'";
					}
				}
				StringBuffer strBuf = new StringBuffer();
				/*strBuf.append("select distinct CircleR as radius,CircleX as lng,CircleY as lat,FenceCorUTime,OrgFen_Type from Organization_FenceList as f ");
				strBuf.append("inner join Organization_DB as d on f.OrganizationID=d.OrganizationID  left join V_VehicleInfo on DB=d.OrganizationID ");
				strBuf.append("where FenceType='Circle' and OrgFen_Type is not null and OrgFen_Type<>'' and f.OrganizationTypeID=1 ");
				strBuf.append("and DBCode in ("+DBCode+") order by f.FenceCorUTime desc ");*/
				//jiyongtian 20141025 IEMS3.6.6.1 电子围栏调整后
				strBuf.append("select distinct OrgFen_RectLeftTX,OrgFen_RectLeftTY,OrgFen_RectRightBX,OrgFen_RectRightBY,FenceCorUTime,OrgFen_Type from Organization_FenceList as f ");
				strBuf.append("inner join Fence_Org on f.FenceID = FenO_FenceID where FenO_OrgCode in ("+DBCode+") and f.OrgFen_State = 1 and f.FenceType = 3 ");
				strBuf.append("and OrgFen_Type is not null and OrgFen_Type<>'' order by f.FenceCorUTime desc ");
				return baseDAO.execQuery(strBuf.toString(), new Object[]{});
			}else{
				return null;
			}
		}

}
